﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.Reflection;

namespace Rookey.Frame.IMClient
{
	static class Global
	{
		public static String ServiceUrl = Config.Instance.ServiceUrl;
		public static String ServerVersion = "";
		public static ContextMenu TrayIconMenu = null;
		public static NotifyIcon TrayIcon = null;
		public static Window Desktop = null;
	}

	static class Program
	{
		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main()
		{
			Config.Instance.Load();
			Global.ServiceUrl = Config.Instance.ServiceUrl;

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			Global.TrayIconMenu = new ContextMenu();
			MenuItem menuItem1 = new MenuItem();
			menuItem1.Text = "退出";
			menuItem1.Click += new EventHandler(menuItem1_Click);
			Global.TrayIconMenu.MenuItems.AddRange(new MenuItem[] { menuItem1 });

			Global.TrayIcon = new NotifyIcon();
			Global.TrayIcon.Icon = Properties.Resources.Tray;
			Global.TrayIcon.Visible = false;
			Global.TrayIcon.ContextMenu = Global.TrayIconMenu;
			Global.TrayIcon.Text = "云骞软件";
			Global.TrayIcon.DoubleClick += new EventHandler(TrayIcon_DoubleClick);

			Global.Desktop = new Window();
			Global.Desktop.Init(
				0, 0, 600 + 6 * 2, 400 + 6 * 2 + 18,
				6, 18,
				false, false, false,
				600 + 6 * 2, 400 + 6 * 2 + 18,
				"桌 面"
			);
			Global.Desktop.ShowInTaskbar = false;
			Global.Desktop.PageLoad += new Window.PageLoadDelegate(Desktop_PageLoad);
			Global.Desktop.IWindow.MoveEx("", 10000, 10000, false);
			Global.Desktop.IWindow.Show();
			Global.Desktop.IWindow.Load(Global.ServiceUrl + "/client.aspx", null);

			Global.TrayIcon.Visible = true;
			Application.Run();
		}

		static void Desktop_PageLoad(object sender, Window.PageLoadEventArgs e)
		{
			if (!e.Result)
			{
				MessageBox.Show("连接服务器错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
				Global.Desktop.Close();
				Global.TrayIcon.Visible = false;
				Application.Exit();
			}
			else
			{
				object core = Utility.GetProperty(Global.Desktop.IWindow.GetHtmlWindow(), "Core");
				object config = Utility.GetProperty(core, "Config");
				Global.ServerVersion = Utility.GetProperty(config, "Version").ToString();

				Global.Desktop.Hide();
			}
		}

		static void menuItem1_Click(object sender, EventArgs e)
        {
            Global.Desktop.Close();
			ReceiveResponseHandler.Global.Stop();
			Global.TrayIcon.Visible = false;
			Application.Exit();
		}

		static void TrayIcon_DoubleClick(object sender, EventArgs e)
		{
			if (SessionImpl.Global.GetSessionID() != "")
			{
				object singletonForm = SessionImpl.Global.GetGlobal("SingletonForm");
				Utility.InvokeMethod(singletonForm, "ShowFriendForm");
			}
		}
	}
}
